package com.frejoys.common.interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.request.AppRequest;
import com.frejoys.common.request.ThreadContext;
import com.frejoys.common.util.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Locale;

/**
 * 全局数据处理
 */
@Component
public class GlobalizationInterceptor implements HandlerInterceptor {

    // 执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // return HandlerInterceptor.super.preHandle(request, response, handler);
        // System.out.println("GlobalizationInterceptor : 开始");
        // 获取语言
        String language = request.getHeader(CommonConstant.language);
        if (StrUtil.isEmpty(language)) {
            language = "zh-CN";
        } else {
            language = language.split(",")[0];
        }

        // 设置线程相关数据
        AppRequest ap = new AppRequest();
        ap.setRoute(request.getRequestURI());
        ap.setTraceId(IdUtil.fastSimpleUUID());
        // ap.setIp(ServletUtil.getClientIP(request, null));
        ap.setIp(IpUtil.getIpAddr(request));
        // 获取文件尺寸
        ap.setFileSize(request.getHeader("File-Size"));
        // site类型
        ap.setSiteType(StrUtil.isNotEmpty(request.getHeader("Site-Type")) ? Integer.valueOf(request.getHeader("Site-Type")) : 0);

        switch (language) {
            case "zh-CN":
                ap.setLocale(Locale.SIMPLIFIED_CHINESE);
                break;
            default:
                ap.setLocale(Locale.US);
                break;
        }

        ThreadContext.set(ap);

        return true;
    }

    // 结束后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        ThreadContext.remove();
        // System.out.println("GlobalizationInterceptor : 结束");
    }

}
